package service

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"wechat-moments_0926/internal/model"
	"wechat-moments_0926/internal/params"
	"wechat-moments_0926/pkg"
)

func RegisterUser(c *gin.Context) {
	var req params.RegisterUserForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var user model.User

	user.Mobile = req.Mobile

	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "账号唯一",
			"data":    "",
		})
		return
	}

	//加盐
	salt := strconv.Itoa(rand.Intn(9000) + 1000)
	user.Salt = salt
	//加密
	user.Password = pkg.MD5(req.Password + salt)
	//注册
	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}

	var info model.UserInfo
	info = model.UserInfo{
		UserId:   int32(user.Id),
		Nickname: req.Nickname,
		Image:    "未设置头像",
		Info:     "未设置签名",
	}
	err = info.AddUserInfo()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "详情添加失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.Id,
	})

}

func LoginUser(c *gin.Context) {
	var req params.RegisterUserForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var user model.User

	user.Mobile = req.Mobile

	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "登陆失败",
			"data":    "",
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	if user.Password != pkg.MD5(req.Password+user.Salt) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    user.Id,
	})

}
